#include <iostream>
#include <cstring>
#include <cstdlib>
#include <poll.h>
#include <unistd.h>

using namespace std;
#define BUFFER 1024

// 简单测试，设置0号文件描述符为读事件监听，每阻塞1kms轮询监听事件是否就绪（poll返回值大于0说明事件就绪）
// 意义：除了网络sock fd可以进行监听事件就绪，默认打开的IO和error流也可以进行事件就绪监听
// 也就是说，管道、文件操作等也能通过多路转接进行事件监听
int main()
{
    struct pollfd Pollfd;
    Pollfd.fd = 0;
    Pollfd.events = POLLIN;
    Pollfd.revents = 0;
    int timeout = 1000;

    char buffer[BUFFER];

    while (true)
    {
        int n = poll(&Pollfd, 1, timeout);
        switch (n)
        {
        case 0:
            cout << "time out....... --> (时间戳: " << (unsigned long)time(nullptr) << ")" << endl;
            break;
        case -1:
            cerr << "select error: " << strerror(errno) << endl;
            exit(0);
            break;
        default:
            ssize_t r = read(Pollfd.fd, buffer, BUFFER - 1);
            if (r > 0)
            {
                buffer[r] = 0;
                cout << "fd["<< Pollfd.fd << "]# " << buffer << endl;
                memset(buffer, 0, BUFFER);
            }
            break;
        }
    }
    return 0;
}